package com.bing.common.component;

import cn.hutool.core.util.ObjectUtil;
import com.bing.common.annotation.DbValue;
import com.bing.common.model.DataProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @Description DataPropertyProcessor
 * @Author Bing
 * @Date 2025/8/5 10:48
 */
@Slf4j
public class DataPropertyProcessor implements BeanPostProcessor {
    // 配置文件
    private final Map<String, Object> propertyMap;
    // 数据属性组件
    private final DataPropertyComponent dataPropertyComponent;

    public DataPropertyProcessor(Map<String, Object> propertyMap,DataPropertyComponent dataPropertyComponent) {
        this.propertyMap = propertyMap;
        this.dataPropertyComponent = dataPropertyComponent;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();
        // 获取监控字段
        initMonitorFields(bean,clazz.getDeclaredFields());
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    /**
     * 获取监控字段
     * @param fields
     * @return
     */
    private void initMonitorFields(Object bean,Field[] fields) {
        for(Field field : fields){
            DbValue annotation = field.getAnnotation(DbValue.class);
            if(ObjectUtil.isNull(annotation)){
                continue;
            }
            String key = extractExpressionContent(annotation.value());
            if(!dataPropertyComponent.isMonitor(key)){
                continue;
            }
            Object value = propertyMap.get(key);
            if(ObjectUtil.isNull(value)){
                continue;
            }
            dataPropertyComponent.addAndSetFieldValue(new DataProperty(key, bean, field),value);
        }
    }

    /**
     * 提取表达式内容（去掉花括号）
     * @param expression 如 "${app.car.reward}" 或 "${app.car.reward:defaultValue}"
     * @return 表达式内容，如 "app.car.reward" 或 "app.car.reward:defaultValue"
     */
    private String extractExpressionContent(String expression) {
        if (expression == null || expression.isEmpty()) {
            return null;
        }
        // 简单直接的方式：去掉开头的 "${" 和结尾的 "}"
        if (expression.startsWith("${") && expression.endsWith("}")) {
            return expression.substring(2, expression.length() - 1);
        }
        return expression;
    }
}